import React, {ChangeEvent, FC, useEffect, useState} from 'react';
import './index.css';
import QuestionCard from '../question-card';
import {Empty, Input} from 'antd';
import {useLocation, useNavigate, useSearchParams} from 'react-router-dom';

/**
 * 问卷接口
 */
interface question{
	// id
	_id: string;
	// 标题
	title: string;
	// 是否发布： 已发布/未发布
	isPublished: boolean;
	// 是否标星
	isStar: boolean;
	// 答卷数量
	answerCount: number;
	// 创建时间
	createdAt: string;
}

/**
 * 标星问卷页面
 */
const Star: FC = () => {
	const navigate = useNavigate();
	const {pathname} = useLocation();
	const [searchParams] = useSearchParams();
	const {Search} = Input;

	/* 问卷数据列表 */
	const [questionList] = useState<question[]>([
		{_id: 'q1', title: '问卷1', isPublished: false, isStar: true, answerCount: 2, createdAt: '2022-03-11 13:05:11'},
		{_id: 'q4', title: '问卷4', isPublished: false, isStar: true, answerCount: 3, createdAt: '2022-03-14 13:05:11'},
	]);
	/* 搜索条件 */
	const [searchValue, setSearchValue] = useState<string>('');

	/**
	 * 搜索条件变化调用方法
	 */
	const searchValueChange = (event: ChangeEvent<HTMLInputElement>) => {
		console.log('searchValueChange -> event.target.value', event.target.value);
		setSearchValue(event.target.value);
	};

	/**
	 * 页面加载前执行函数
	 */
	useEffect(() => {
		// 获取路径中的搜索参数
		setSearchValue(searchParams.get('keyword') || '');
	}, [searchParams]);

	/**
	 * 搜索条件变化调用方法
	 */
	const search = (value: string) => {
		console.log('search -> value', value);
		// 跳转到当前页面，并且附带搜索参数
		navigate({
			pathname,
			search: `keyword=${searchValue}`,
		});
	};

	return (
		<div className="question-list">
			{/* 头部 */}
			<div className="question-list-header">
				{/* 头部左侧 */}
				<div className="question-list-header-left">
					<h2>标星问卷</h2>
				</div>
				{/* 头部右侧 */}
				<div className="question-list-header-right">
					<Search
						style={{width: 200}}
						allowClear
						value={searchValue}
						onChange={searchValueChange}
						onSearch={search}
						placeholder="请输入关键字"
					/>
				</div>
			</div>

			{/* 身体 */}
			<div className="question-list-content">
				{
					questionList.length > 0 ?
						questionList.map((question) => {
							return <QuestionCard key={question._id} {...question}/>;
						})
						:
						<Empty/>
				}
			</div>

			{/* 尾部 */}
			<div className="question-list-footer">
				footer
			</div>
		</div>
	);
};

export default Star;